package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 * @date 2023/5/17 9:53
 */

/**
 * 检查用户是否登录
 */
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取访问路径
        String requestURI = request.getRequestURI();
        //定义放行路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/user/sendMsg"
        };

        //定义一个方法,判断是否需要拦截
        boolean check = check(urls, requestURI);

        //不需要,直接放行
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }

        //判断电脑端登录状态,已经登录,直接放行
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee != null) {
            BaseContext.setId(employee);
            filterChain.doFilter(request, response);
            return;
        }
        //判断移动端登录状态,已经登录,直接放行
        Long user = (Long) request.getSession().getAttribute("user");
        if (user != null) {
            BaseContext.setId(user);
            filterChain.doFilter(request, response);
            return;
        }

        //没有登录跳转登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 判断是否拦截
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
